package com.fulu.netty.luban.onereactor;

import java.io.IOException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

/**
 * 处理客户端连接类
 */
public class Accpetor implements Runnable {
    // 服务端的server
    private final ServerSocketChannel serverSocketChannel;

    // 集合对象，专门用来存socket
    private final Selector selector;

    /**
     * 构造器
     * @param serverSocketChannel  服务端的server
     * @param selector  集合对象，专门用来存socket
     */
    public Accpetor(ServerSocketChannel serverSocketChannel, Selector selector) {
        this.serverSocketChannel = serverSocketChannel;
        this.selector = selector;
    }

    @Override
    public void run() {
        try {
            // 接收client连接请求
            SocketChannel socketChannel = serverSocketChannel.accept();
            System.out.println(socketChannel.getRemoteAddress().toString());
            if(socketChannel != null){
                socketChannel.configureBlocking(false); //设置非阻塞
                SelectionKey key = socketChannel.register(selector, SelectionKey.OP_READ);//socketChannel向selector注册一个OP_READ事件，返回该通道的key
                selector.wakeup(); // 使一个阻塞住的selector操作立即返回。
                key.attach(new TCPHandler(key, socketChannel));
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
